//
//  RMDateBaseManager.m
//  RMNote
//
//  Created by lanou3g on 16/4/15.
//  Copyright © 2016年 lxf. All rights reserved.
//

#import "RMDateBaseManager.h"
#import "NSDate+Calendar.h"
@interface RMDateBaseManager ()
@property(nonatomic,strong)FMDatabaseQueue * queue;
@end 

@implementation RMDateBaseManager

+ (instancetype)defaultManager{
    static RMDateBaseManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[RMDateBaseManager alloc]init];
    });
    return manager;
}

- (instancetype)init{
    if (self = [super init]) {
        //获取Documents路径
        NSString * string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        //创建数据库路径
        NSString * path = [string stringByAppendingPathComponent:kRMNoteSqlite];
        NSLog(@"path = %@",path);
        //打开数据库
        self.dataBase = [[FMDatabase alloc]initWithPath:path];

        self.queue = [FMDatabaseQueue databaseQueueWithPath:path];
        BOOL isOpen = [self.dataBase open];
        if (!isOpen) {
            NSLog(@"打开数据库失败");
        }
    }
    return self;
}

- (void)closeDB{
    [self.dataBase close];
}

//mark!!!:创建表
- (void)createTable:(NSString *)tableName{
    NSString * string = [NSString stringWithFormat:@"create table if not exists %@ (RMDate date,RMModel blob,Year text,Month text,Day text)",tableName];
    BOOL isCreate = [self.dataBase executeUpdate:string];
    if (isCreate) {
        NSLog(@"创建表成功 %@",tableName);
    }else{
        NSLog(@"创建表失败");
    }
}

//mark!!!:增 1
- (BOOL)insertIntoTable:(NSString *)tableName createDate:(NSDate *)date Model:(RMBaseModel *)model{
     NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
     NSString * string = [NSString stringWithFormat:@"insert into %@ (RMDate,RMModel,Year,Month,Day) values (?,?,?,?,?)",tableName];
    BOOL result ;
    @synchronized(self) {
      result = [self.dataBase executeUpdate:string withArgumentsInArray:@[date,data,date.year,date.month,date.day]];
    }


     return result;
}

//mark!!!:删 1
- (BOOL)deleteNoteFromTableName:(NSString *)tableName byCreateDate:(NSDate *)date{
    NSString * string = [NSString stringWithFormat:@"delete from %@ where RMDate = ?",tableName];
   BOOL result = [self.dataBase executeUpdate:string withArgumentsInArray:@[date]];
//    BOOL result = [self.dataBase executeUpdate:string];
    return result;
}

//mark!!!:批量删除
- (BOOL)deleteNoteFromTableName:(NSString *)tableName withArray:(NSArray *)array{
    __block BOOL result = YES;
    [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        for (NSDate * date in array) {
            result = result && [self deleteNoteFromTableName:tableName byCreateDate:date];
        }
        if (!result) {
            *rollback = YES;
            return ;
        }
    }];
    return result;
}

//mark!!!:改
- (BOOL)updateNoteFromTableName:(NSString *)tableName  withModel:(RMBaseModel *)model byCreateDate:(NSDate *)date{
     NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
    NSString * string = [NSString stringWithFormat:@"update %@ set RMModel = ? where RMDate = ?",tableName];
    BOOL result = [self.dataBase executeUpdate:string withArgumentsInArray:@[data,date]];
//    BOOL result = [self.dataBase executeUpdate:string];
    return result;

}

//mark!!!:查询 1
- (NSArray *)selectNoteFromTable:(NSString *)tableName{
    NSMutableArray * array = [[NSMutableArray alloc]init];
    NSString * string = [NSString stringWithFormat:@"select * from %@",tableName];
    FMResultSet * result = [self.dataBase executeQuery:string];
    while ([result next]) {
        
        NSData * data = [result dataForColumn:@"RMModel"];
        RMBaseModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [array addObject:model];
    }
    return array;
}

-(NSArray *)selectNotebySQLStr:(NSString *)sqlStr{
    NSMutableArray * array = [[NSMutableArray alloc]init];
    NSString * string = sqlStr;
    FMResultSet * result = [self.dataBase executeQuery:string];
    while ([result next]) {
        
        NSData * data = [result dataForColumn:@"RMModel"];
        RMBaseModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [array addObject:model];
    }
    return array;
}

-(NSArray *)selectCreateDateFromTable:(NSString *)tableName{
    NSMutableArray * array = [[NSMutableArray alloc]init];

    NSString * string = [NSString stringWithFormat:@"select * from %@",tableName];
    FMResultSet * result = [self.dataBase executeQuery:string];
    while ([result next]) {
        
        NSDate * date = [result dateForColumn:@"RMDate"];
        
        [array addObject:date];
    }
    return array;
}

//mark!!!:根据时间查表中的model
- (NSArray *)selectNoteFromTable:(NSString *)tableName byCreateDate:(NSDate *)date{
    NSMutableArray * array = [[NSMutableArray alloc]init];
    NSString * string = [NSString stringWithFormat:@"select * from %@ where RMDate = ? ",tableName];
   FMResultSet * result = [self.dataBase executeQuery:string withArgumentsInArray:@[date]];
//    FMResultSet * result = [self.dataBase executeQuery:string];
    while ([result next]) {
        NSData * data = [result dataForColumn:@"RMModel"];
        RMBaseModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [array addObject:model];
    }
  return array;
}

@end
